package cn.harry.modular.sys.controller;

import cn.harry.common.annotation.SysLog;
import cn.harry.common.api.R;
import cn.harry.common.enums.BusinessType;
import cn.harry.common.utils.SecurityUtils;
import cn.harry.modular.sys.domain.SysUser;
import cn.harry.modular.sys.service.SysUserService;
import cn.hutool.core.util.ArrayUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * ClassName: SysUserController Description:
 *
 * @author honghh Date 2019/10/15 12:42 Copyright (C) www.tech-harry.cn
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@Tag(name = "sys-user => 用户管理")
@RequestMapping("/sys/user")
public class SysUserController {

    private final SysUserService sysUserService;

    /**
     * @param params 参数内容 current 当前页 size 每页显示条数 username 用户名称 phone 手机号 deptId 部门ID
     */
    @Operation(summary = "list 获取用户列表")
    @Parameters({
            @Parameter(name = "current", description = "当前页", required = true, example = "1"),
            @Parameter(name = "size", description = "每页显示条数", required = true, example = "10"),
            @Parameter(name = "username", description = "用户名称"),
            @Parameter(name = "phone", description = "手机号"),
            @Parameter(name = "deptId", description = "部门ID"),
            @Parameter(name = "beginTime", description = "开始时间"),
            @Parameter(name = "endTime", description = "结束时间"),
            @Parameter(name = "status", description = "状态"),
    })
    @GetMapping(value = "/list")
    @PreAuthorize("@ss.hasPermission('system:user:list')")
    public R<IPage<SysUser>> list(@Parameter(hidden = true) @RequestParam Map<String, Object> params) {
        IPage<SysUser> page = sysUserService.getPage(params);
        return R.success(page);
    }

    @Operation(summary = "{id} 根据用户ID获取详细信息")
    @GetMapping("/{id}")
    @PreAuthorize("@ss.hasPermission('system:user:query')")
    public R<SysUser> getById(@PathVariable("id") Long id) {
        return R.success(sysUserService.getUserById(id));
    }

    @Operation(summary = "更新用户信息")
    @SysLog(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @PreAuthorize("@ss.hasPermission('system:user:edit')")
    public R<Integer> update(@RequestBody SysUser user) {
        boolean res = sysUserService.updateUser(user);
        return res ? R.success() : R.failed();
    }

    @Operation(summary = "新增用户信息")
    @SysLog(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    @PreAuthorize("@ss.hasPermission('system:user:add')")
    public R<Integer> create(@RequestBody SysUser user) {
        boolean res = sysUserService.createUser(user);
        return res ? R.success() : R.failed();
    }

    @Operation(summary = "updateStatus/{id} 修改用户状态")
    @PreAuthorize("@ss.hasPermission('system:user:edit')")
    @SysLog(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/updateStatus/{id}")
    public R<Integer> updateStatus(@PathVariable Long id, String status) {
        return sysUserService.updateStatus(id, status) ? R.success() : R.failed();
    }

    @Operation(summary = "resetPwd/{id} 重置密码")
    @PreAuthorize("@ss.hasPermission('system:user:edit')")
    @SysLog(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/resetPwd/{id}")
    public R<Integer> resetPwd(@PathVariable Long id, String password) {
        // 判断是否有权限修改
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            return R.failed("非管理员无权修改");
        }
        return sysUserService.updatePasswordByUserId(id, password) ? R.success()
                : R.failed();
    }

    @Operation(summary = "{ids} 删除用户")
    @PreAuthorize("@ss.hasPermission('system:user:remove')")
    @SysLog(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping(value = "/{ids}")
    public R<Integer> deleteByIds(@Parameter(description = "多个以英文逗号(,)拼接") @PathVariable Long[] ids) {
        if (ArrayUtil.contains(ids, SecurityUtils.getUserId())) {
            return R.failed("当前用户不能删除");
        }
        boolean count = sysUserService.deleteByIds(ids);
        return count ? R.success() : R.failed();
    }

    @Operation(summary = "export 按条件导出（不分页）")
    @PreAuthorize("@ss.hasPermission('system:user:export')")
    @SysLog(title = "用户管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public R export(HttpServletResponse response,
                    @RequestParam Map<String, Object> params) {
        List<SysUser> list = sysUserService.getExportList(params);
        try {
            EasyExcel.write(response.getOutputStream(), SysUser.class).sheet("用户管理")
                    .doWrite(list);
            return R.success();
        } catch (IOException e) {
            log.error("用户管理,导出失败 error:{}", e.getMessage());
        }
        return R.failed();

    }

    @Operation(summary = "importTemplate 下载模板")
    @SysLog(title = "用户管理", businessType = BusinessType.EXPORT)
    @GetMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        EasyExcel.write(response.getOutputStream(), SysUser.class).sheet("用户管理")
                .doWrite(ArrayList::new);
    }

}
